package com.ruoyi.framework.config;

import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component("wechatApiSecurity")
public class WechatApiSecurity {

    private final Logger logger = LoggerFactory.getLogger(WechatApiSecurity.class);

    public static final String KEY = "zhangfen";
    public boolean check( HttpServletRequest httpRequest){
// String token = request.getParameter("token");
        String token = httpRequest.getHeader("token");
        String timestamp = httpRequest.getHeader("timestamp");
        String sign = httpRequest.getHeader("sign");
        if (StringUtils.isBlank(token) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(sign)) {// 非法请求

            logger.info("----鉴权错误:有head不完整----");
            logger.info("token :"+token);
            logger.info("timestamp : "+timestamp);
            logger.info("sign : "+sign);
            return false;
        }
        // 1、判断token是否存在，暂时不管，因为不管是从数据库查询还是缓存到redis，都影响效率
//		if(JedisUtils.get(token) == null){
//			return false;
//		}

        // 2、判断时间戳是否在当前5分钟内，防止重放攻击
        //FIXME  接口测试期，先取消，部署后启用
//		Date requestDate = new Date(Long.parseLong(timestamp));
//		Date now = new Date();
//		if(now.after(DateUtils.addMinutes(requestDate, 5))){
//			return false;
//		}

        // 3、判断签名是否合法
        String input = token + timestamp + KEY;
        String check = DigestUtils.md5Hex(input);
        if (sign.equals(check)) {
            return true;
        }
        logger.info("token :"+token);
        logger.info("timestamp : "+timestamp);
        logger.info("sign : "+sign);
        logger.info("----鉴权错误: 签名失败");
        return false;
    }
}
